package com.iee.guava.collections;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/** ArrayListMultimap相当于是对我们常用列表业务操作进行封装，在处理列表业务较多的项目，引入Guava能够降低我们代码复杂度，更专注于核心业务实现。
 */
 public class ArrayListMultimapDemo {

    public static void main(String[] args) {
        List<Order> orderList = Lists.newArrayList();
        Order order = new Order();
        order.setUserId("u1");
        order.setOrderId("o1");
        Order order2 = new Order();
        order2.setUserId("u1");
        order2.setOrderId("o2");
        Order order3 = new Order();
        order3.setUserId("u2");
        order3.setOrderId("o3");

        orderList.add(order);
        orderList.add(order2);
        orderList.add(order3);

        group(orderList);

        guavaGroup(orderList);
    }

    /**
     * 自己实现分组
     */
    public static void group(List<Order> orderList) {
        Map<String, List<Order>> userOrdersMap = new HashMap<>();
        for(Order order: orderList) {
            String userId = order.getUserId();
            if(userOrdersMap.containsKey(userId)) {
                userOrdersMap.get(userId).add(order);
            } else {
                List<Order> orders = new ArrayList<>();
                orders.add(order);
                userOrdersMap.put(order.getUserId(), orders);
            }
        }
        System.out.println("userOrdersMap>>>>>>>>>"+userOrdersMap);
    }
    /**
     * 使用Guava进行分组分组
     */
    public static void guavaGroup(List<Order> orderList) {
        ArrayListMultimap<String, Order> arrayListMultimap = ArrayListMultimap.create();
        orderList.forEach(e -> arrayListMultimap.put(e.getUserId(), e));
        System.out.println("arrayListMultimap>>>>" + arrayListMultimap);
        // ArrayListMultimap 常用API asMap() get(key)返回值为List<T>
    }
}

